// @Author EthanScriptOn
// @Desc
package log_worker

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/pool"
	"gitee.com/fatzeng/srf_switch_basic_components/queue"
	"gitee.com/fatzeng/srf_switch_log/log_filter"
	"gitee.com/fatzeng/srf_switch_log/log_task"
)

type LoggerCollectWorker struct {
	*pool.DefaultWorker
}

func GenerateLoggerCollectWorker(queue queue.Queue, weight int) *LoggerCollectWorker {
	return &LoggerCollectWorker{
		DefaultWorker: pool.GenerateDefaultWorker(queue, weight),
	}
}

func (l *LoggerCollectWorker) FilterOption(task pool.Task) (err error) {
	unitTask, ok := task.(*log_task.LogUnitTask)
	if !ok {
		return fmt.Errorf("LoggerCollectWorker Submit task error task is %v", task)
	}
	if canPassThrough, err := l.filter(unitTask); err != nil || !canPassThrough {
		return fmt.Errorf("LoggerCollectWorker Submit task can not pass through task is %v msg is %v", task, err)
	}
	return
}

func (l *LoggerCollectWorker) filter(unitTask *log_task.LogUnitTask) (bool, error) {
	snapshot := unitTask.GetUnit()
	rule := unitTask.GetRule()
	for _, rTag := range rule.RulesTag {
		checker, canFound := log_filter.DefaultFilterChecker.GetChecker(rTag)
		if !canFound {
			return false, fmt.Errorf("rule with ID '%s' does not exist", rTag)
		}
		canPassThrough, err := checker(snapshot)
		if err != nil {
			return false, fmt.Errorf("unable to pass verification with name : [%+v]  err : [%+v]", rTag, err)
		}
		if !canPassThrough {
			return false, nil
		}
	}
	return true, nil
}
